<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/axios@0.12.0/dist/axios.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/lodash@4.13.1/lodash.min.js"></script>
</head>

<body>
    <div id='app'>
        <div><input v-model="question"></div>
        <div>{{ answer }}</div>
    </div>
    <script>
        var app = new Vue({
            el: "#app",
            data: {
                question: "",
                answer: "请输入你的问题，结尾加上问号？",
            },
            watch: {
                question: function (v) {
                    console.log("question变化了" + v);
                    this.answer = "请把问题输完"
                    this.debouncedGetAnswer()//自由取名
                    console.log("debouncedGetAnswer被調用了")
                }
            },
            created: function () {//給debouncedGetAnswer賦值_.debounce(this.getAnswer, 500)
                this.debouncedGetAnswer = _.debounce(this.getAnswer, 1000)//getAnswer可以自己取名，第二个1000代表每1000毫秒调用一次debouncedGetAnswer方法
            },
            methods: {//判斷輸入框里是否带问号
                getAnswer: function () {
                    if (this.question.indexOf('?') === -1) {
                        this.answer = "问题通常加上问号"
                        return
                    }
                    this.answer = '思考中...'
                    var vm = this//把this方法存入vm
                    axios.get('https://yesno.wtf/api')
                        .then(function (response) {//_.capitalize返回(response.data.answer)的值
                            vm.answer = _.capitalize(response.data.answer)
                        })
                        .catch(function (error) {//捕捉错误返回异常
                            vm.answer = '你的问题我没有看懂' + error
                        })
                }
            }
        });
    </script>
</body>

</html>